package com.example.demo.controller;

import com.example.demo.pojo.Cart;
import com.example.demo.pojo.Dto.CartDto;
import com.example.demo.service.CartService;
import com.example.demo.utill.ResponseResult;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Resource
    private CartService cartService;

    @RequestMapping("/toCart")
    @ResponseBody
    public ResponseResult insertToCart(int userid, int goodsid, double price, int nums){
        ResponseResult result=new ResponseResult();
        Cart cart=cartService.selectGoods(userid,goodsid);
        if(cart!=null){
            int id=cart.getId();
            cartService.updateGoods(id,nums);
            result.setCode(200);
            result.setMessage("加入购物车成功");
        }else{
            int i=cartService.insertToCart(userid,goodsid,price,nums);
            if(i!=0){
                result.setCode(200);
                result.setMessage("加入购物车成功");
            }
            else{
                result.setCode(500);
                result.setMessage("加入购物车失败");
            }
        }
        return result;
    }

    @RequestMapping("/seeCart")
    @ResponseBody
    public ResponseResult seeCart(int userid){
        List<CartDto> list =cartService.selectAllGoods(userid);
        ResponseResult res=new ResponseResult();
        res.setData(list);
        res.setCode(200);
        res.setMessage("购物车数据查询成功");
        return  res;
    }

    @RequestMapping("/update")
    @ResponseBody
    public ResponseResult update(int id,int nums){
        int i=cartService.updateGoods(id,nums);
        ResponseResult res=new ResponseResult();
        if(i!=0){
            res.setCode(200);
            res.setMessage("修改成功");
        }else{
            res.setCode(500);
            res.setMessage("修改失败");
        }
        return res;
    }

    @RequestMapping("/todel")
    @ResponseBody
    public ResponseResult delete(int id,int userid) {
        int i = cartService.delGoods(id);
        List<CartDto> list =cartService.selectAllGoods(userid);
        ResponseResult res = new ResponseResult();
        if (i != 0) {
            res.setCode(200);
            res.setMessage("删除成功");
            res.setData(list);
        } else {
            res.setCode(500);
            res.setMessage("删除失败");
        }
        return res;
    }

    @RequestMapping("/queryIds")
    @ResponseBody
    public ResponseResult queryIds(int[] ids){
        ResponseResult res=new ResponseResult();
        res.setCode(200);
        res.setData(cartService.queryIds(ids));
        return res;
    }
}
